package org.marsdonne.commons.jpa;

import lombok.Getter;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import java.util.Calendar;
import java.util.Date;

@Getter
public class DateFieldFilter extends BasedFieldFilter {
    private Date startWith;
    private Date endWith;

    public DateFieldFilter() {
        this.endWith = new Date();
        this.startWith = generateDefaultValueBy(this.endWith, -7);
    }

    public DateFieldFilter(int amountOfDate) {
        this.endWith = new Date();
        this.startWith = generateDefaultValueBy(this.endWith, amountOfDate);
    }

    private Date generateDefaultValueBy(Date basedDate, int amountOfDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(basedDate);
        calendar.add(Calendar.DAY_OF_MONTH, amountOfDate);
        return calendar.getTime();
    }

    public void setStartWith(Date startWith) {
        this.startWith = startWith;
        if (this.endWith == null)
            this.endWith = generateDefaultValueBy(this.startWith, 7);
    }

    public void setEndWith(Date endWith) {
        this.endWith = endWith;
        if (this.startWith == null)
            this.startWith = generateDefaultValueBy(this.endWith, -7);
    }

    @Override
    public Predicate generateCriteria(CriteriaBuilder builder, Path field) {
        return builder.between(field, startWith, endWith);
    }
}
